/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.deal;

import controller.pagination;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.dao.*;
import model.pojo.*;

/**
 *
 * @author DucThien
 */
@WebServlet(name = "deal", urlPatterns = {"/deal"})
public class deal extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if(request.getParameter("action") != null){
               String action = request.getParameter("action");
                if("view_detail".equals(action)){                   
                    getDealDetail(request, response); 
                }else if("pagination".equals(action)){
                    PaginationDeal(request, response);
                }else if("filterListDeal".equals(action)){
                    filterListDeal(request, response); 
                }else if("updateQuantityBuy".equals(action)){
                    if(request.getParameter("dealId") != null && request.getParameter("customerId") != null){
                        updateQtyDealSold(Integer.parseInt(request.getParameter("dealId")),Integer.parseInt(request.getParameter("customerId")),out);  
                    }   
                }
            }else{
                getListDeal(request, response);
            }
            
        } finally {            
            out.close();
        }
    }
    public void filterListDeal(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String dealName = "";
        String dealerName = "";
        float percentDiscount = 0;
        String dealerAddress = "";
        float fromCost = 0;
        float toCost = 0;
        String url = "";
        
        if(request.getParameter("dealName") != null){           
           dealName = request.getParameter("dealName");
           dealName = new String(dealName.getBytes("ISO-8859-1"),"UTF-8");
           url += "&dealName="+URLEncoder.encode(dealName, "UTF-8");
        }
        if(request.getParameter("dealerName") != null){
           dealerName = request.getParameter("dealerName");
           dealerName = new String(dealerName.getBytes("ISO-8859-1"),"UTF-8");
           url += "&dealerName="+URLEncoder.encode(dealerName,"UTF-8");
        }
        if(request.getParameter("percentDiscount") != null){
           percentDiscount = Float.parseFloat(request.getParameter("percentDiscount"));
           url += "&percentDiscount="+percentDiscount;
        }
        if(request.getParameter("dealerAddress") != null){
           dealerAddress = request.getParameter("dealerAddress");
           dealerAddress = new String(dealerAddress.getBytes("ISO-8859-1"),"UTF-8");
           url += "&dealerAddress="+URLEncoder.encode(dealerAddress,"UTF-8");
        }
        if(request.getParameter("fromCost") != null){
           fromCost = Float.parseFloat(request.getParameter("fromCost"));
           url += "&fromCost="+fromCost;
        }   
        if(request.getParameter("toCost") != null){
           toCost = Float.parseFloat(request.getParameter("toCost"));
           url += "&toCost="+toCost;
        }
        int page = 1;
        int limit = 6;
        if(request.getParameter("page") != null){
            page = Integer.parseInt(request.getParameter("page"));
        }
        dealDAO dDAO = new dealDAO();
        List<Deal> listDeal = dDAO.filterDeal(dealerName, dealName, percentDiscount, dealerAddress, fromCost, toCost, ((page-1)*limit) , limit);
        ArrayList<Map<String,Object>> listDealInfo = new ArrayList<Map<String, Object>>();
        for(int i=0 ; i<listDeal.size();i++){
            // each deal
            Deal d = listDeal.get(i);
            Map<String,Object> eachDeal = new HashMap<String, Object>();
            eachDeal.put("dealId",d.getDealId());
            eachDeal.put("decreaseCost", d.getDecreaseCost());
            eachDeal.put("buyCost",d.getBuyCost());
            eachDeal.put("percentDiscount", d.getPercentDiscount());
            eachDeal.put("quantityDealSold", d.getQuantityDealSold());
            eachDeal.put("quantityDealRemaining", d.getQuantityDealRemaining());
            eachDeal.put("startTime", d.getStartTime());
            eachDeal.put("endTime", d.getEndTime());
            eachDeal.put("view", d.getViews());
            productDAO pDAO = new productDAO();
            Product p = pDAO.getProductByProductID(d.getProductId());
            eachDeal.put("dealName", p.getName());
            eachDeal.put("cost", p.getCost());
            eachDeal.put("description", p.getDescription().substring(0, 100));
            productBannerDAO prBannerDAO = new productBannerDAO();
            List<ProductBanner> listProductBanner = prBannerDAO.getListProductBannerByProductID(d.getProductId());
            eachDeal.put("banner", listProductBanner.get(0).getBanner());
            listDealInfo.add(eachDeal); 
        }
        int total = dDAO.filterDeal(dealerName, dealName, percentDiscount, dealerAddress, fromCost, toCost, -1 , -1 ).size() ;    
        pagination pagi = new pagination();
        pagi.setPage(page);
        pagi.setLimit(limit);
        pagi.setTotalOnThis(total); 
        pagi.setUrl("./deal?action=filterListDeal&page={page}"+url); 
        out.println(renderListDeal(listDealInfo,pagi.renderPagination())); 
    }
    public void getListDeal(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        provinceDAO prDAO = new provinceDAO();
        List<Object> listProvince =  prDAO.getListProvince();
        request.setAttribute("arrayProvince", listProvince);
        String url="content_deal.jsp";
        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);  
    }
    public void PaginationDeal(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int page = 1;
        int limit = 9;
        if(request.getParameter("page") != null){
            page = Integer.parseInt(request.getParameter("page"));
        }
        dealDAO dDAO = new dealDAO();
        List<Deal> listDeal = dDAO.getListDeal((page-1) * limit,limit);
        ArrayList<Map<String,Object>> listDealInfo = new ArrayList<Map<String, Object>>();
        

        for(int i=0 ; i<listDeal.size();i++){
            // each deal
            Deal d = listDeal.get(i);
            Map<String,Object> eachDeal = new HashMap<String, Object>();
            eachDeal.put("dealId",d.getDealId());
            eachDeal.put("decreaseCost", d.getDecreaseCost());
            eachDeal.put("buyCost",d.getBuyCost());
            eachDeal.put("percentDiscount", d.getPercentDiscount());
            eachDeal.put("quantityDealSold", d.getQuantityDealSold());
            eachDeal.put("quantityDealRemaining", d.getQuantityDealRemaining());
            eachDeal.put("startTime", d.getStartTime().getDate());
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            eachDeal.put("endTime", dt1.format(d.getEndTime())); 
            eachDeal.put("view", d.getViews());
            productDAO pDAO = new productDAO();
            Product p = pDAO.getProductByProductID(d.getProductId());
            eachDeal.put("dealName", p.getName());
            eachDeal.put("cost", p.getCost());
            eachDeal.put("description", p.getDescription().substring(0, 100));
            productBannerDAO prBannerDAO = new productBannerDAO();
            List<ProductBanner> listProductBanner = prBannerDAO.getListProductBannerByProductID(d.getProductId());
            eachDeal.put("banner", listProductBanner.get(0).getBanner());
            listDealInfo.add(eachDeal); 
        }
        
        pagination pagi = new pagination();
        pagi.setTotalOnThis(dDAO.totalDeal());
        pagi.setPage(page);
        pagi.setLimit(limit); 
        pagi.setUrl("./deal?action=pagination&page={page}"); 
        out.println(renderListDeal(listDealInfo,pagi.renderPagination())); 
    }
    //public String
    public String renderListDeal(ArrayList<Map<String,Object>> listDealInfo , String outputPagination){
          String result = "";         
          result  += outputPagination;
          result  += "<div class='box-heading'>";
                  for(int i=0 ; i<listDealInfo.size();i++){ 
           result += "<div class='box-product'>"                             
                      + "<div class='box-outside'>"          
                       + "<div class='box-inside'>"             
                       + "<div class='name'>"                 
                       + "<p>"+listDealInfo.get(i).get("dealName") +"</p>"                     
                        + "</div>"                
                        + "<div class='image'>"                 
                        + "<a onclick='showDealDetail("+listDealInfo.get(i).get("dealId") +")' href='javascript:;'>"                    
                         + "<img  src='"+listDealInfo.get(i).get("banner") +"' width='242' height='120'  alt='"+listDealInfo.get(i).get("dealName") +"' />"                        
                          + "</a>"                   
                          + "</div>"               
                          + "<div class='information'>"               
                          + "<table width='90%'>"                   
                           + " <tr>"                     
                           + " <td colspan='2' style='padding-bottom: 5px;'>"                         
                           + " <p style='width:230px; overflow:hidden; padding: 0 10px; font-weight: normal;'>"+listDealInfo.get(i).get("description") +"</p>"                             
                            + " </td>"                        
                            + " </tr>"                    
                            + "<tr>"                     
                             + " <td style='padding:10px;'>"                       
                             + "<span style='font-weight: bold ; font-size: 22px; color:maroon;'>"                            
                              + listDealInfo.get(i).get("buyCost")                             
                              + "</span> " +"<span style='font-weight: bold ; font-size: 12px; color:maroon;'>VND</span>"                          
                              + "<br/>"                            
                               + "<span style='text-decoration: line-through;color:#6C6C6C; font-style: italic;'>"+listDealInfo.get(i).get("cost") +"VND</span>"                          
                               + "</td>"                      
                                + "<td> <div onclick='showDealDetail("+listDealInfo.get(i).get("dealId") +")' class='buy_now'>View Now</div> </td>"                     
                                 + "</tr>"                
                                 + "<tr bgcolor='#C3DEF7'>"                
                                 + "<td colspan='2'>"                    
                                 + "<table width='100%' >"                        
                                 + "<tr>"                            
                                + "<td style='padding: 5px 0; text-align: center;'>view <br /> "+listDealInfo.get(i).get("view") +"</td>"                                 
                                + "<td style='text-align: center;'>quantity buyer <br />"+listDealInfo.get(i).get("quantityDealSold") +"</td>"                                 
                                 + "<td style='text-align: center;'>time remaining <br /><div id='deal_"+listDealInfo.get(i).get("dealId")+"' class='count_down' title='"+listDealInfo.get(i).get("endTime")+"'></div></td>"                                
                                + "</tr>  "                                                   
                                + "</table>"                         
                                + "</td>"                     
                                + "  </tr>"               
                                 + "  </table>"          
                              + " </div>  "                                           
                               + "</div>"      
                              + " </div> "                     
                      + "</div>";     
                              }    
                  
                 result += "</div>" + outputPagination;
                
        return result;
    }
    public void getDealDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
         
         if(request.getParameter("deal_id") != null){
            int dealId = Integer.parseInt(request.getParameter("deal_id"));
            dealDAO dDAO = new dealDAO();
            Deal d = dDAO.getDealById(dealId);
            request.setAttribute("deal", d);
            String[] conditions = d.getConditionOfUse().split("-");
            request.setAttribute("array_condition", conditions);
            dealerDAO dlDAO = new dealerDAO();
            Dealer dl = dlDAO.getDealerByDealerID(d.getDealerId());
            request.setAttribute("dealer", dl);
            productDAO proDAO = new productDAO();
            Product p = proDAO.getProductByProductID(d.getProductId());
            request.setAttribute("product", p);
            productBannerDAO proBanDAO = new productBannerDAO();
            List<ProductBanner> pn = proBanDAO.getListProductBannerByProductID(d.getProductId());
            request.setAttribute("array_banner", pn);
            dealLocationDAO dloDAO = new dealLocationDAO();
            List<DealLocation> dlo = dloDAO.getListDealLocationByDealID(dealId);
            request.setAttribute("array_deal_map", dlo);
            dealSoldDAO ds = new dealSoldDAO();
            List<Customer> lds = ds.getListDealSoldByDealID(dealId);
            request.setAttribute("listDealSold", lds); 
            if(request.getParameter("deal_top") != null){
                request.setAttribute("flag_deal_top", "has");
            }
            HttpSession session1 = request.getSession();
            if(session1.getAttribute("user_login") != null){
                customerDAO cDAO = new customerDAO();
                int idCustomer = cDAO.getCustomerByUsername(session1.getAttribute("user_login").toString()).getCustomerId();
                dealSoldDAO dsolDAO = new dealSoldDAO();
                boolean checkExistsCusForDeal = dsolDAO.checkCustomerExistsWithDeal(dealId, idCustomer);
                if(checkExistsCusForDeal == false){
                    request.setAttribute("customerIdDealSold", idCustomer);
                }
            }
            String url="content_deal_detail.jsp";
            RequestDispatcher rd = request.getRequestDispatcher(url);
            rd.forward(request, response);
         }
           
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(deal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(deal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void updateQtyDealSold(int dealId , int customerId , PrintWriter out) {
        //throw new UnsupportedOperationException("Not yet implemented");
        dealDAO dDAO = new dealDAO();
        Deal d = dDAO.getDealById(dealId);
        int QtyCurrent = d.getQuantityDealSold() + 1;
        d.setQuantityDealSold(QtyCurrent);
        d.setQuantityDealRemaining(d.getQuantityDealRemaining() - 1); 
        dDAO.saveOrUpdate(d);
        dealSoldDAO dsDAO = new dealSoldDAO();
        dsDAO.saveOrUpdate(new DealSold(dealId, customerId));
        out.print(String.valueOf(QtyCurrent)); 
    }

   
}
